<template>
  <div class="TPosition">
    <el-input v-model="innerValue" :placeholder="placeholder">
      <el-button slot="append" icon="el-icon-location-outline" @click="openDialog"></el-button>
    </el-input>
    <el-dialog
      v-if="visible"
      :visible="visible"
      title="位置选择"
      width="1000px"
      append-to-body
      class="t-dialog"
      :before-close="hanldeClose"
    >
      <div class="m-[16px]">
        <el-form :model="form" label-width="70px" label-suffix="：" label-position="left">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="搜索地址">
                <el-input id="searchInput" v-model="form.keywords" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="当前地址">
                <el-input v-model="form.name" :disabled="true">
                  <template slot="prepend">{{ form.district }}</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 容器 -->
        <div id="container" class="mb-[16px]"></div>
      </div>
      <footer class="common-t-drawer-footer">
        <t-button class="common-search-btn" type="primary" @click="handleConfirm">提 交</t-button>
        <t-button class="common-search-btn" type="default" plain @click="hanldeClose">取 消</t-button>
      </footer>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader"; // 引入
import vModelMixin from "@/mixin/v-model";
//打开弹窗

export default {
  name: "TPosition",
  mixins: [vModelMixin],
  props: {
    placeholder: {
      type: String,
      required: true,
      default: "请输入",
    },
    lat: {
      type: String,
      required: false,
      default: "",
    },
    lng: {
      type: String,
      required: false,
      default: "",
    },
  },
  data() {
    return {
      map: null,
      autoOptions: {
        input: "searchInput", // searchInput输入框的id
      },
      placeSearch: null,
      auto: null,
      visible: false,
      form: {
        keywords: "",
        district: "",
        name: "",
        lat: "",
        lng: "",
      },
      addres: "",
      districtList: "",
      cityCode: "",
    };
  },
  methods: {
    // 初始化地图
    initMap() {
      AMapLoader.load({
        key: "81ca1ec8ea4cbabe83900122086d18bb", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.AutoComplete", "AMap.PlaceSearch"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [this.lng ? this.lng : 113.29, this.lat ? this.lat : 31.88], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.HawkEye());
          this.auto = new AMap.AutoComplete(this.autoOptions); // AutoComplete提示插件
          this.placeSearch = new AMap.PlaceSearch({
            // 搜索插件
            map: this.map,
          });
          const marker1 = new AMap.Marker({
            position: [this.lng ? this.lng : 113.29, this.lat ? this.lat : 31.88],
            title: this.innerValue ? this.innerValue : "随县",
          });
          this.map.add(marker1);
          // 绑定select事件
          this.auto.on("select", this.select);
          if (this.lng) {
            this.form.lng = this.lng;
          }
          if (this.lat) {
            this.form.lat = this.lat;
          }
          if (this.innerValue) {
            const index = this.innerValue.indexOf("区");
            if (index != -1) {
              this.form.district = this.innerValue.slice(0, index + 1);
              this.form.name = this.innerValue.slice(index + 1, this.innerValue.length);
            } else {
              const lastIndex = this.innerValue.indexOf("市");
              this.form.district = this.innerValue.slice(0, lastIndex + 1);
              this.form.name = this.innerValue.slice(lastIndex + 1, this.innerValue.length);
            }
          } else {
            this.form.district = "湖北省随州市";
            this.form.name = "随县";
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    select(e) {
      const { district, name, location, adcode } = e.poi;
      this.form.district = district;
      this.form.name = name;
      if (location) {
        this.form.lat = location.lat;
        this.form.lng = location.lng;
      } else {
        this.form.lat = "";
        this.form.lng = "";
      }
      this.getCode(e.poi.location.lng, e.poi.location.lat, true, e.poi.name);
      this.marker(e.poi.location.lng, e.poi.location.lat, this.map, true);
    },
    recursion(list, code) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].citycode == code) {
          this.cityCode = list[i].adcode;
          return;
        }
        if (list[i].districtList && list[i].districtList.length > 0) {
          this.recursion(list[i].districtList, code);
        }
      }
    },
    getCode(lng, lat, type, name) {
      const that = this;
      const district = null;
      AMap.plugin(["AMap.Geocoder", "AMap.DistrictSearch"], function () {
        // 引入 Geocoder 逆向地理编码插件，把经纬度转为地址
        const geocoder = new AMap.Geocoder({
          radius: 1000, // 以给定坐标为中心点，单位：米。取值范围：0-3000。默认值：1000
          extensions: "all", // 返回信息的详略。默认值：base，返回基本地址信息；取值为：all，返回地址信息及附近poi、道路、道路交叉口等信息
          batch: true,
        });
        const lnglat = [lng, lat];
        geocoder.getAddress(lnglat, async (status, result) => {
          await that.recursion(that.districtList, result.regeocode.addressComponent.citycode);
          // 传入经纬度，根据给定坐标进行解析，把经纬度转为地址
          const obj = {
            placeName: type ? name : result.regeocode.pois[0].name,
            cityCode: that.cityCode,
            placeLon: lng,
            placeLat: lat,
          };

          that.$emit("MapObj", obj);
          that.addres = type ? name : result.regeocode.pois[0].name;
        });
      });
    },
    // 根据点击事件或者搜索事件生成坐标点
    marker(lat, lng, map, type) {
      const marker = new AMap.Marker({
        position: new AMap.LngLat(lat, lng), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: "当前位置",
      });
      if (type) {
        this.map.setCenter([lat, lng]);
      }
      this.map.clearMap(); //清除所有遮罩物
      this.map.add(marker);
    },
    //提交
    handleConfirm() {
      this.$message.success("选择地址成功");
      this.visible = false;
      this.form.keywords = "";
      this.$emit("handleConfirm", this.form);
    },
    //取消
    hanldeClose() {
      this.form.keywords = "";
      this.visible = false;
    },
    //打开弹窗
    openDialog() {
      this.visible = true;
      this.$nextTick(() => {
        this.initMap();
      });
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 500px;
  padding: 0;
  margin: 0;
}
</style>
